package org.agile4j.math.iterative;

/**
 * SquareRoot class
 * <p>
 * 计算大于1的正整数的平方根
 * 使用迭代法-二分法
 *
 * @author hanyx
 * @date 2018/12/15
 */
public class SquareRoot {

    public static void main(String[] args) {
        int number = 9;
        double squareRoot = SquareRoot.cacle(number, 0.000001, 10000);
        if (squareRoot == -1) {
            System.out.println("必须是正整数");
        } else if (squareRoot == -2.0) {
            System.out.println("没找到");
        } else {
            System.out.println(String.format("%d 的平方根是 %f", number, squareRoot));
        }
    }

    /**
     *
     * @param n 要记算的数
     * @param deltaThresold 误差的阈值
     * @param maxTry 二分查找最大次数
     * @return
     */
    private static double cacle(int n, double deltaThresold, int maxTry) {
        if (n <= 1) {
            return -0.1;
        }

        double min = 1;
        double max = (double) n;
        for (int i = 0; i < maxTry; i++) {
            double middle = (min + max) / 2;
            double square = middle * middle ;
//            double delta = Math.abs((square/n)-1);
            double delta = Math.abs((square-n)/n); // 3.162277 相对误差
//            double delta = Math.abs(square-n); // 3.162278  绝对误差
            System.out.println("delta: " + delta);
            if (delta <= deltaThresold){
                return middle;
            } else {
                if (square>n){
                    max = middle;
                } else if (square<n){
                    min = middle;
                }
            }

//            if (square > n) {
//                max = middle /2;
//            } else if (square <0){
//                min = middle;
//            } else {
//                return middle;
//            }
        }

        return 0.0;
    }
}
